package bootstrap

import (
	"errors"
	"fmt"
	"myblogs/Lib"
	"myblogs/Lib/redis"
	"myblogs/app/variable"
	"os"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
)

func readYaml(configPath string, env string) {
	config := viper.New()
	if strings.TrimSpace(configPath) != "" {
		config.AddConfigPath(configPath)
	} else {
		config.AddConfigPath("./config")
	}
	config.SetConfigName(fmt.Sprintf("config_%s.yml", env))
	config.SetConfigType("yaml")

	readContent(config)
}

func readContent(config *viper.Viper) {
	if err := config.ReadInConfig(); err != nil {
		var configFileNotFoundError viper.ConfigFileNotFoundError
		if errors.As(err, &configFileNotFoundError) {
			fmt.Println("找不到配置文件.......")
		}
	}

	// 读取配置文件
	variable.Port = config.GetString("server.port")
	variable.DbHost = config.GetString("mysql.host")
	variable.DbPort = config.GetString("mysql.port")
	variable.DbUser = config.GetString("mysql.user")
	variable.DbPassword = config.GetString("mysql.password")
	variable.ImgHost = config.GetString("image.host")
	variable.Env = config.GetString("profiles.active")

	variable.RedisHost = config.GetString("redis.host")
	variable.RedisPort = config.GetInt("redis.port")
	variable.RedisPass = config.GetString("redis.pass")

}

func init() {
	//env := os.Getenv("ENVIRONMENT")

	// 获取命令行参数
	args := os.Args

	var env string
	var configPath string

	// 遍历并打印命令行参数
	for i, arg := range args {
		params := strings.Split(arg, "=")
		if len(params) == 2 {
			switch params[0] {
			case "--env", "-env":
				env = params[1]
			case "--configPath", "-configPath":
				configPath = params[1]
			}
		}
		fmt.Printf("参数 %d: %s\n", i, arg)
	}

	if len(env) == 0 {
		panic("环境参数必须设置")
	}

	if env == "prod" {
		gin.SetMode(gin.ReleaseMode)
	}

	/*fmt.Print("请输入数据库Host Port root password\n")
	_, _ = fmt.Scanln(&variable.DbHost, &variable.DbPort, &variable.DbUser, &variable.DbPassword)

	fmt.Print("请输入图片Host\n")

	_, _ = fmt.Scanln(&variable.ImgHost)
	if len(variable.ImgHost) == 0 {
		variable.ImgHost = "http://192.168.10.132:20191/img/"
	}
	*/

	readYaml(configPath, env)

	fmt.Printf("env: %s\n", env)
	fmt.Printf("profile.active: %s\n", variable.Env)
	fmt.Printf("ServerPort: %s\n", variable.Port)
	fmt.Printf("DbHost: %s %s %s %s \n", variable.DbHost, variable.DbPort, variable.DbUser, variable.DbPassword)
	fmt.Printf("ImgHost: %s \n", variable.ImgHost)

	if dbMysql, err := Lib.GetMysqlDbClient(); err != nil {
		panic(err)
	} else {
		variable.Db = dbMysql
	}

	redis.InitRedis()
}
